package com.mateng.treasurechest.view.recipe.adapter

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.mateng.treasurechest.R
import com.mateng.treasurechest.model.recipe.bean.CategoryBean
import com.mateng.treasurechest.utils.PreferencesUtils
import com.mateng.treasurechest.view.recipe.SP

/**
* Created by mateng on 2018/1/25.
*/
class RecipeAllCategoryAdapter(private var context: Context, private var childBeans: List<CategoryBean.ResultBean.ChildsBeanX>?) : RecyclerView.Adapter<RecipeAllCategoryAdapter.ViewHolder>() {

    private var afterClientPosition: Int = 0

    var onItemClickListener: OnItemClickListener? = null

    override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
        childBeans?.get(position)?.categoryInfo?.isChecked?.let {
            holder?.itemView?.isSelected = it
        }
        holder?.tvCategoryName?.text = childBeans?.get(position)?.categoryInfo?.name

        holder?.itemView?.setOnClickListener({
            if (afterClientPosition == position)
                return@setOnClickListener
            childBeans?.get(afterClientPosition)?.categoryInfo?.isChecked = false
            afterClientPosition = position
            childBeans?.get(position)?.categoryInfo?.isChecked = true
            notifyDataSetChanged()

            onItemClickListener?.onItemClick(position)
        })

    }

    override fun getItemCount(): Int {
        return childBeans?.size ?: 0
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {

        return ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_recipe_big_category, parent, false))
    }


    fun setNewData(childBeans: List<CategoryBean.ResultBean.ChildsBeanX>) {
        if (childBeans.isNotEmpty()) {
            this.childBeans?.get(afterClientPosition)?.categoryInfo?.isChecked = false
            this.childBeans = childBeans
            this.afterClientPosition = PreferencesUtils.getInt(context, SP.SP_KEY_RECIPE_TYPE_POSITION, 0, SP.SP_NAME_RECIPE_CACHE)
            childBeans[afterClientPosition].categoryInfo?.isChecked = true
            onItemClickListener?.onItemClick(afterClientPosition)
        }
        notifyDataSetChanged()
    }


    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvCategoryName: TextView = itemView.findViewById(R.id.tv_category_name)
    }


}